package com.design.framework.validata;

import java.util.Iterator;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import com.design.framework.validata.bean.ValidationResult;

/**
 * 检验实体工厂
 * @author JohnDeng
 * @dateTime 2020年6月20日下午11:37:58	
 *
 * @param <T>
 */
public class ValidatorBeanFactory<T> {

	public boolean validataBean(T t, ValidationResult result,Class<?>... groups) {
		// 通过 Validation 构造 DefaultValidatorFactory 工厂
		ValidatorFactory hvf = Validation.buildDefaultValidatorFactory();
		// 通过 ValidatorFactory 获取 validate
		Validator validator = hvf.getValidator();
		// 通过 Validator 验证   实例 返回 ConstraintViolation<T> 集合
		Set<ConstraintViolation<T>> cvs = validator.validate(t, groups);
		// 获取 迭代器
		Iterator<ConstraintViolation<T>> ite = cvs.iterator();
		while (ite.hasNext()) {
			ConstraintViolation<T> cv = ite.next();
			// 获取 验证错误 信息 message
			result.setMessage(cv.getMessage());
			// 获取错误的字段名称
			result.setPath(cv.getPropertyPath());
			return true;
		}
		return false;
	}

}
